<template>
  <view :class="[`${prefixCls}-agreements-container`]" v-if="agreements.length">
    <!-- 行内 -->
    <view class="template-inline" v-if="needAgreements && mode === 'inline'">
      <view class="content">
        <uv-checkbox-group v-model="isAgree" @change="setAgree">
          <uv-checkbox label="阅读并同意" name="isAgree" :activeColor="theme" />
        </uv-checkbox-group>
        <view class="agreements">
          <text class="item" v-for="(agreement, index) in agreements" :key="index" @click="navigateTo(agreement)"> {{ agreement.title }} </text>
        </view>
      </view>
    </view>

    <!-- 弹窗式 -->
    <uv-modal ref="agreementsModal" title="隐私政策提示" :asyncClose="true" :closeOnClickOverlay="false" v-if="needAgreements && mode === 'modal'">
      <view class="template-modal">
        <view class="notice">您正在访问的APP页面及服务由{{ $Env.GlobAppTitle }}提供支持，如有疑问请阅读一下相关服务信息！</view>
        <view class="content" v-html="argeementInfo.default_value"> </view>
        <div class="agreements">
          <text class="item" v-for="(agreement, index) in agreements" :key="index" @click="navigateTo(agreement)"> {{ agreement.title }} </text>
        </div>
      </view>
      <template #confirmButton>
        <view class="operate-button">
          <uv-button type="primary" shape="circle" @click="onConfirm">同意并继续</uv-button>
          <uv-text type="info" size="28rpx" align="center" :customStyle="{ marginTop: '20rpx' }" text="不同意，进入浏览模式" @click="onCancel" />
        </view>
      </template>
    </uv-modal>
  </view>
</template>

<script>
import { isEmpty } from '@/common/helper/is'
import { mapGetters, mapMutations, mapState } from 'vuex'
let retryFun = () => {}
/**
 * cu-agreements
 * @description 服务协议和隐私政策条款组件: 作用于哪种场景如：1.注册（包括登录并注册，如：微信登录、苹果登录、短信验证码登录）、2.登录（如：用户名密码登录）、3.实名认证
 * @property {String} mode = [inline|modal] // 协议展示风格:inline:行内展示；modal:模态框展示
 * @property {String} scope = [register|login|realNameVerify|agreement]
 * @property {Boolean} agreement = true | false // 同意协议状态，绑定v-model的任意字段
 */
export default {
  name: 'cuAgreements',
  props: {
    mode: {
      type: String,
      default: 'inline',
    },
    scope: {
      type: String,
      default() {
        return 'register'
      },
    },
    agreement: {
      type: Boolean,
      default: false,
    },
  },
  model: {
    //event:什么时候触发v-model行为
    event: 'change',
    // 定义传递给v-model的那个变量，绑定到哪个属性值上
    prop: 'agreement',
  },
  data() {
    // { title: '苏享家隐私政策摘要', subtitle: 'zhaiyao' },
    return {
      needAgreements: true,
      agreements: [
        { title: '《用户协议》', url: `/pages/subpackage/privacy-policy/privacy-detail?title=用户协议&subtitle=user_agreement` },
        { title: '《隐私政策》', url: `/pages/subpackage/privacy-policy/privacy-detail?title=隐私政策&subtitle=privacy_policy` },
        // { title: '《第三方SDK清单》', url: `${Env.ApiBaseDomain}/mobile/suzhou/agreement/third-sdk` },
      ],
      scopeList: ['register', 'login', 'realNameVerify', 'agreement'],
    }
  },
  watch: {
    // 监听是否弹出隐私协议
    dialogIsAgree: {
      immediate: true,
      handler(nv) {
        this.$nextTick(() => {
          if (this.mode === 'modal') {
            if (!Number.isFinite(nv) && !nv) this.$refs.agreementsModal.open()
            else this.$refs.agreementsModal.close()
          }
        })
      },
    },
  },
  computed: {
    ...mapState('app', ['dialogIsAgree', 'argeementInfo']),
    ...mapGetters(['theme']),
    isAgree: {
      get() {
        return this.agreement ? ['isAgree'] : []
      },
      set(e) {
        this.$emit('change', !isEmpty(e) ? true : false)
      },
    },
  },
  options: {
    styleIsolation: 'shared', // 组件样式隔离方式，具体配置选项参见 https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#%E7%BB%84%E4%BB%B6%E6%A0%B7%E5%BC%8F
  },
  methods: {
    ...mapMutations('app', ['SET_ISAGREE']),

    open(Fun) {
      this.$nextTick(() => {
        if (Fun) {
          retryFun = Fun
        }
        this.$refs.agreementsModal.open()
      })
    },

    navigateTo({ url, title }) {
      this.$ROUTE.go(url)
    },

    setAgree(e) {
      this.isAgree = e
    },

    onConfirm() {
      this.SET_ISAGREE(1)
      this.$refs.agreementsModal.close()
      retryFun()
    },

    onCancel() {
      this.SET_ISAGREE(0)
      this.$refs.agreementsModal.close()
    },
  },
  created() {
    this.needAgreements = (this.scopeList || []).includes(this.scope)
    const curPage = getCurrentPages().pop()
    retryFun = () => {
      curPage.$vm?.getData && curPage.$vm.getData()
    }
  },
}
</script>

<style lang="scss" scoped>
.#{prefixCls('agreements-container')} {
  position: relative;
  .template-inline,
  .template-modal {
    .content {
      @include flex;
      font-size: 24rpx;
      color: $uv-content-color;
      ::v-deep .uv-checkbox-group {
        flex: none;
        .uv-checkbox .uv-checkbox__label-wrap text {
          color: $uv-content-color;
        }
      }
    }
    .agreements {
      @include flex;
      .item {
        font-size: 24rpx;
        color: $uv-primary;
      }
    }
  }

  .template-inline {
    @include flex;
    padding: 20rpx 0;
    .content {
      flex-wrap: wrap;
    }
    .agreements {
      margin-left: 36rpx;
    }
  }

  .template-modal {
    .notice {
      margin-bottom: 20rpx;
      text-indent: 48rpx;
    }
    .content {
      max-height: 400rpx;
      overflow: auto;
    }
    .agreements {
      margin-top: 20rpx;
    }
  }
  .operate-button {
    @include flex(column);
    padding: 0 50rpx 50rpx 50rpx;
  }
}
</style>
